<template>
    <div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="分组名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入分组名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="loopGroupList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="分组名称" align="center" prop="name"/>
            <el-table-column label="排序" align="center" prop="orderNum"/>
            <el-table-column label="是否可用" align="center" prop="status"/>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改控制点分组对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="分组名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入分组名称"/>
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <el-input v-model="form.orderNum" placeholder="请输入排序"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>

            <el-button @click="addLoop">添加控制点</el-button>
            <el-table :data="form.dataList" :height="250">
                <el-table-column label="网关" align="center" prop="gatewayId">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.gatewayId"
                                   placeholder="选择网关"
                        >
                            <el-option
                                v-for="item in gatewayList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                @click.native="tableChangeGateway(item.value, scope.$index)"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="控制点" align="center" prop="loopId">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.loopId"
                                   placeholder="选择控制点"
                        >
                            <el-option
                                v-for="item in scope.row.loopSelect"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-link style="margin-left: 5px" type="danger" :underline="false"
                                 @click="deleteLoop(scope.row, scope.$index)"
                        >删除
                        </el-link>
                    </template>
                </el-table-column>

            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listLoopGroup, getLoopGroup, delLoopGroup, addLoopGroup, updateLoopGroup } from '@/api/business/loopGroup'
import { listSelectByGatewayId } from '@/api/equipment/loop'
import { listSelect } from '@/api/equipment/gateway'

export default {
    name: 'LoopGroup',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 控制点分组表格数据
            loopGroupList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                orderNum: null,
                status: null
            },
            // 表单参数
            form: {},
            gatewayList: [],
            // 表单校验
            rules: {
                name: [
                    { required: true, message: '请输入分组名称', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getList()
        this.getGatewayList()
    },
    methods: {

        getList() {
            this.loading = true
            listLoopGroup(this.queryParams).then(response => {
                this.loopGroupList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        cancel() {
            this.open = false
            this.reset()
        },

        reset() {
            this.form = {
                id: null,
                name: null,
                orderNum: null,
                projectId: null,
                status: '0',
                dataList: [],
                loopIds: [],
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },

        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },

        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加控制点分组'
        },

        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getLoopGroup(id).then(response => {
                this.form = response.data
                this.open = true
                this.title = '修改控制点分组'
            })
        },
        // 添加控制点
        addLoop() {
            let obj = {
                gatewayId: null,
                loopId: null,
                loopSelect: []
            }
            this.form.dataList.push(obj)
        },
        tableChangeGateway(gatewayId, index) {
            this.form.dataList[index]['loopId'] = null
            listSelectByGatewayId(gatewayId).then(response => {
                this.form.dataList[index]['loopSelect'] = response.data
            })
        },
        deleteLoop(row, index) {
            this.form.dataList.splice(index, 1)
        },
        // 获取网关数据
        getGatewayList() {
            listSelect().then(response => {
                this.gatewayList = []
                for (let item of response.data) {
                    let temp = {}
                    temp['value'] = item.gatewayId
                    temp['label'] = item.gatewayName
                    temp['serverOnline'] = item.serverOnline
                    this.gatewayList.push(temp)
                }
            })
        },
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.form.loopIds = []
                    let length = this.form.dataList.length
                    for (let i = 0; i < length; i++) {
                        let loopId = this.form.dataList[i]['loopId']
                        if (loopId !== undefined && loopId != null) {
                            this.form.loopIds.push(loopId)
                        }
                    }
                    console.log('loopIds..', this.form.loopIds)
                    if (this.form.loopIds.length === 0) {
                        this.$message.error('请选择控制点')
                        return
                    }
                    if (this.form.id != null) {
                        updateLoopGroup(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addLoopGroup(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除控制点分组编号为"' + ids + '"的数据项？').then(function() {
                return delLoopGroup(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('business/loopGroup/export', {
                ...this.queryParams
            }, `loopGroup_${new Date().getTime()}.xlsx`)
        }
    }
}
</script>
